package com.example.hw_smart_home.huawei_api.device;

import com.example.hw_smart_home.huawei_api.auth.Authentication;
import com.example.hw_smart_home.huawei_api.util.Constants;
import com.example.hw_smart_home.huawei_api.util.HttpUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class QueryDevice {

/*    public static String getDeviceInfo() throws Exception {

        String projectId = Constants.PROJECT_ID_LT; //项目ID
        String deviceId = Constants.DEVICE_ID_LT;  //设备ID
        String nodeId = "DHTT";  //设备标识码
        String deviceCommandUrl = Constants.DEVICE_COMMAND_URL; //查询设备
        String deviceShadowUrl = Constants.DEVICE_SHADOW_URL;   //查询设备影子

        String deviceCommandAttribute = getAttribute(projectId, deviceId, deviceCommandUrl, "DHT", nodeId);
        String deviceShadowAttribute = getAttribute(projectId, deviceId, deviceShadowUrl, "DHT", nodeId);

        StringBuilder result = new StringBuilder();
        ObjectMapper objectMapper = new ObjectMapper();

        if (!deviceCommandAttribute.equals("0")) {
            JsonNode jsonNode = objectMapper.readTree(deviceCommandAttribute);
            String statusStr = jsonNode.get("status").asText();
            result.append("设备状态: ").append(statusStr.equals("ONLINE") ? "在线" : "离线").append("\n");
        }

        if (!deviceShadowAttribute.equals("0")) {
            JsonNode jsonNode = objectMapper.readTree(deviceShadowAttribute)
                    .get("shadow").get(0).get("reported").get("properties");
            if (jsonNode.has("Temperature")) {
                result.append("温度: ").append(jsonNode.get("Temperature").asText()).append("\n");
            }
            if (jsonNode.has("Humidity")) {
                result.append("湿度: ").append(jsonNode.get("Humidity").asText()).append("\n");
            }
        }

        return result.toString();
    }*/

    public static String getAttribute(String projectId, String deviceId, String url, String serviceID, String nodeId) throws Exception {
        String token = Authentication.getToken();
        url = String.format(url, projectId, deviceId);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Auth-Token", token);

        Map<String, String> params = new HashMap<>();
        params.put("service_id", serviceID);
        params.put("node_id", nodeId);

        HttpUtils httpUtils = new HttpUtils();
        String responseBody = httpUtils.doGetWithHeaders(url, headers, params);

        if (responseBody == null || responseBody.isEmpty()) {
            return "0";
        } else {
            return responseBody;
        }
    }
}
